﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using log4net;

namespace NormalGsearch
{
    class GoogleTrendsProxy
    {
        private NormalGSearchViewModel viewModel;
        private GoogleAuthenticationProxy authenticationProxy;
        private ILog logger;

        private string SampleString = "Top-Suchanfragen\nfacebook,100\ngoogle,85\nebay,80\nyoutube,75\namazon,45\nwetter,45\nmaps,40";

        public GoogleTrendsProxy(NormalGSearchViewModel viewModel, GoogleAuthenticationProxy authenticationProxy)
        {
            this.viewModel = viewModel;
            this.authenticationProxy = authenticationProxy;
            logger = LogManager.GetLogger(typeof(GoogleTrendsProxy)); 
        }

        public List<string> GetSearchTerms()
        {
            viewModel.StatusMessage = "Ermittlung von Google Trend Suchwörtern";
            List<string> searchTerms;

            byte[] csv = null;
            logger.Info("Retrieving Google Trend words ...");

            try
            {
                using (var client = new WebClient())
                {
                    client.Headers.Add("Authorization", "GoogleLogin " + authenticationProxy.SecureId);
                    csv = client.DownloadData(string.Format("https://www.google.de/trends/trendsReport?geo=DE&date=10%2F2014%201m&cmpt=q&content=1&export=1"));                    
                }                              
            }
            catch (Exception ex)
            {
                logger.Error("Retrieving Google Trend words failed: " + ex);
            }

            string resultAsString;
            if (csv != null && csv.Length > 0)
            {
                resultAsString = Encoding.UTF8.GetString(csv, 0, csv.Length);
                searchTerms = RetrieveSearchTerms(resultAsString);

                if (searchTerms.Count == 0)
                {
                    logger.Error("Retrieving Google Trend words failed: " + resultAsString);
                    logger.Error("Using sample Google Trend words instead!");
                    searchTerms = RetrieveSearchTerms(SampleString);
                }
            }
            else
            {
                logger.Error("Using sample Google Trend words instead!");
                searchTerms = RetrieveSearchTerms(SampleString);                
            }

            return searchTerms;
        }

        private List<string> RetrieveSearchTerms(string resultString)
        {
            List<string> searchTerms = new List<string>();

            char[] separators = new char[] { '\n' };
            // split string in lines
            string[] lines = resultString.Split(separators);

            // iterate through lines            
            foreach (string line in lines)
            {
                int commaIndex = line.IndexOf(',');

                if (commaIndex >= 0)
                {
                    string searchTerm = line.Substring(0, commaIndex);
                    Console.WriteLine(searchTerm);
                    searchTerms.Add(searchTerm);
                }
            }

            return searchTerms;
        }
    }
}
